package com.tianyi.controller.login;


import com.tianyi.controller.BaseController;
import com.tianyi.controller.sysUser.SysUserController;
import com.tianyi.lib.model.WebResult;
import com.tianyi.lib.req.SysUserReq;
import com.tianyi.model.SimpleLoginUser;
import com.tianyi.sysUser.SysUserService;
import com.tianyi.util.EncryptUtil;
import com.tianyi.util.SimpleUserUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 *
 * @author cuixuhui
 */
@Controller
@RequestMapping("user")
public class LoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public WebResult<SimpleLoginUser> login(@RequestParam String loginParam, @RequestParam String pwd, HttpServletResponse response){
        System.out.println(loginParam+pwd);
        WebResult<SimpleLoginUser> loginUser = sysUserService.login(loginParam, pwd);
        if (!loginUser.isSuccess()) {
            return loginUser;
        }
        SimpleUserUtils.addUser2Cookie(response, loginUser.getData());
        SimpleLoginUser loginUserBack = getUserFromRequest();
        return WebResult.ok(loginUserBack);
    }

    /**
     * 获取登陆用户
     * @return
     */
    @RequestMapping(value = "getLoginUser", method = RequestMethod.GET)
    @ResponseBody
    public WebResult<SimpleLoginUser> getLoginUser(){
        SimpleLoginUser userFromReq = getUserFromRequest();
        if (Objects.isNull(userFromReq)){
            return WebResult.error("用户未登陆");
        }

        return WebResult.ok(userFromReq);
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response){
        SimpleUserUtils.deleteCookieByName(request, response, SimpleUserUtils.USER_TOKEN);
        return "/index.html";
    }
}
